package sk.mangos.realmd;

import com.sun.deploy.util.ArrayUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;

/**
 * @author sk.z
 */
public class AuthSocketExample {

    private static final int LISTEN_PORT = 3724;    //服务器监听端口
    private static final int READ_LENGTH = 16;      //块长度

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(LISTEN_PORT);
        System.out.println("start ...");

        while (true) {
            Socket socket = serverSocket.accept();
            InputStream input = socket.getInputStream();

            byte[] result = new byte[0];
            int desIndex = 0;

            byte[] block = new byte[READ_LENGTH];
            int length;
            while ((length = input.read(block)) != -1) {
                result = Arrays.copyOf(result, desIndex + length);
                System.arraycopy(block, 0, result, desIndex, length);
                desIndex = desIndex + length;

                if (length != READ_LENGTH) {
                    break;
                }
            }

            printBytes(result);


            OutputStream output = socket.getOutputStream();
            output.write(new byte[]{'e','n','d'});

            output.close();
            input.close();
            socket.close();
        }
    }

    private static void printBytes(byte[] array) {
        for (byte b : array) {
            System.out.print(b);
            System.out.print("|");
        }
        System.out.println();
        System.out.println(new String(array));
    }
}
